import math

from django.core.paginator import Paginator
from django.http import JsonResponse
from django.shortcuts import render

# Create your views here.
from django.views import View
from django.core import serializers

from user.models import Suggest
import os, django

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Project.settings")  # project_name 项目名称
django.setup()


class Index(View):
    def get(self, request):
        suggest_list = Suggest.objects.all()
        pagelist = range(1, math.ceil(len(suggest_list) / 4) + 1)
        max_page = max(pagelist)
        page = request.GET.get('page')
        print(page)
        if page:
            page = int(page)
        else:
            page = 1
        suggest_list = suggest_list[(page - 1) * 4:page * 4]
        try:
            login = request.session['user']
            if login:
                if request.is_ajax():
                    suggest_list = serializers.serialize("json", suggest_list)
                    return JsonResponse({'login': 'true', 'suggests': suggest_list, 'page': page, 'max_page': max_page})
                return render(request, 'index.html',
                              {'login': 'true', 'suggests': suggest_list, 'page': page, 'max_page': max_page})
            return render(request, 'index.html',
                          {'suggests': suggest_list, 'page': page, 'max_page': max_page})
        except:
            if request.is_ajax():
                suggest_list = serializers.serialize("json", suggest_list)
                return JsonResponse({'login': 'true', 'suggests': suggest_list, 'page': page, 'max_page': max_page})
            return render(request, 'index.html',
                          {'suggests': suggest_list, 'page': page, 'max_page': max_page})
